package com.liuyang.demo.scanpackage;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.DependsOn;
import org.springframework.core.type.filter.AssignableTypeFilter;
import org.springframework.core.type.filter.RegexPatternTypeFilter;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;

@Service
public class AnimalFactory {
    Map<AnimalEnum,IAnimal> map =new HashMap<>();

    @Autowired
    ApplicationContext applicationContext;
    @Autowired
    SpringContextUtil springContextUtil;

    @PostConstruct
    private void init (){
        Class interfaceClazz = IAnimal.class;
        ClassScanner classScanner = new ClassScanner();
        classScanner.addIncludeFilter(new AssignableTypeFilter(interfaceClazz));
        classScanner.addExcludeFilter(new RegexPatternTypeFilter(Pattern.compile(interfaceClazz.getName())));
        Set<Class<?>> scan = classScanner.scan(interfaceClazz.getPackage().getName());
        scan.forEach(clazz->{
            IAnimal bean = (IAnimal) applicationContext.getBean(clazz);
            //IAnimal bean = springContextUtil.getBean(clazz);
            map.put(bean.getType(),bean);
        });
    }

    public IAnimal getInstance(AnimalEnum animalEnum){
        return map.get(animalEnum);
    }
}
